//
//  OAuthViewController.swift
//  sxwb
//
//  Created by TianDu on 2016/11/16.
//  Copyright © 2016年 TianDu. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController{

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        let rightBar = UIBarButtonItem(title: "填充", style: .done, target: self, action: #selector(fillPsw))
        self.navigationItem.rightBarButtonItem = rightBar
        
        let leftBar = UIBarButtonItem(title: "返回", style: .done, target: self, action: #selector(clickToBack))
        self.navigationItem.leftBarButtonItem = leftBar
        
        
        let url :URL = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKay)&redirect_uri=\(RedirectUri)")!
        
        webView.loadRequest(URLRequest(url: url))
        webView.delegate = self
    }
    
    @objc private func clickToBack() {
        
        dismiss(animated: true, completion: nil)
    }

    @objc private func fillPsw() {
        
        let jsCode = "document.getElementById('userId').value='sunxiao0603@sina.cn';document.getElementById('passwd').value='weiba2012!!!';"
        
        webView.stringByEvaluatingJavaScript(from: jsCode)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension OAuthViewController:UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
        SVProgressHUD.showError(withStatus: "加载失败")
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url else {
            return true
        }
        
        let urlStr = url.absoluteString
        
        guard (urlStr.contains("code=")) else {
            return true
        }
        
        let code = urlStr.components(separatedBy: "=").last!
        
        requestAccessToken(code)
        
        return false
    }
}

extension OAuthViewController{
    
    fileprivate func requestAccessToken(_ code:String) {
        
        let parameters = ["client_id":AppKay,"client_secret":AppSecret,"grant_type":"authorization_code","code":code,"redirect_uri":RedirectUri]
        
        RequestManager.share.request(.Post, url: TokenUrl, parameters: parameters, finished: {(result:Any?, error:Error?) -> () in

            guard error == nil else{
                print(error!)
                return
            }
            

            let dic = result as! [String:Any]
        
            let user = UserAccount(dic)
            print(user)
            
            self.getUserInfo(user)
        })
    }
    
    fileprivate func getUserInfo(_ account:UserAccount){
        
        guard let token = account.access_token else {
            return
        }
        
        guard let uid = account.uid else {
            return
        }
        
        RequestManager.share.request(.Get, url: "https://api.weibo.com/2/users/show.json", parameters: ["access_token":token,"uid":uid], finished: {(result:Any?, error:Error?) -> () in
            
            if error != nil{
                print(error!)
                return
            }

            guard let dict = result as? [String:Any] else{
                return
            }
            account.avatar_large = dict["avatar_large"] as? String
            account.screen_name = dict["screen_name"] as? String
            print(account)
            
            //将account 进行归档保存到沙盒中(归档解档的对象必须遵守nscoding协议)
            // 1.获取沙盒路径
            let docuPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
            let filePath = docuPath + "/account.plist"
            NSKeyedArchiver.archiveRootObject(account, toFile: filePath)
            
            print(filePath)
        })
    }
}
